import React, { createContext, useContext, useMemo, useState } from "react";

interface ISearchData {
    folder?: string;
    name?: string;
    type?: string;
    timestamp?: string|number;
}

type IFileApiEvents = {
    onSearch: (searchData: ISearchData) => void;
    onRefresh: () => void;
    onUpdateSize: () =>void;
}
type GetArgsType<T> = T extends (...args: infer P) => any ? P : never; //推断函数参数类型




interface IFileApi {
    filterType?: string;
    searchData: ISearchData;
    selectedList: string[];
    search(searchData: ISearchData): void;
    refresh(): void;
    on<EventName extends keyof IFileApiEvents>(event: EventName, callback: IFileApiEvents[EventName]): Function;
    emit<EventName extends keyof IFileApiEvents>(event: EventName, ...args: GetArgsType<IFileApiEvents[EventName]>): void;
}

const FileContext = createContext<any>({});

export const FileProvider = ({ children, selectedList, filterType }: any) => {
    const [ searchData, setSearchData ] = useState<ISearchData>({
        type: filterType
    });
    const [ eventListener ] = useState<any>({});
    const fileContext = useMemo(() => ({
        searchData,
        selectedList,
        filterType,
        search(searchData: ISearchData) {
            setSearchData(searchData)
        },
        refresh() {
            setSearchData({
                ...searchData,
                timestamp: Date.now()
            });
        },
        on: (name: string, callback: any) => {
            eventListener[name] = callback;
            return () => {
                delete eventListener[name];
            }
        },
        emit: (name: string, ...args: any[]) => {
            return eventListener[name] && eventListener[name](...args);
        }
    }), [searchData, selectedList, filterType]);
    return <FileContext.Provider value={fileContext}>{children}</FileContext.Provider>;
};

export const useFileApi = (): IFileApi => {
    const context = useContext(FileContext);
    return context;
};